﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AnalisisDeRiesgosConfiguration.Model;
using MySql.Data.MySqlClient;
using AnalisisDeRiesgosConfiguration.Exceptions;
using System.Security.Cryptography;

namespace AnalisisDeRiesgosConfiguration.DataAccess
{
    class UserDataAccess
    {
        DatabaseConnectionString connectionString;

        public UserDataAccess(DatabaseConnectionString theConnectionString)
        {
            connectionString = theConnectionString;
        }

        public void CreateUser(User theUser)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString.ConnectionStringDB))
                {
                    connection.Open();
                    string sql = "INSERT INTO user " +
                                "(CI,firstName,lastName,secondLastName,username,password, privilege) " +
                                "VALUES " +
                                "(@CI, @firstName, @lastName, @secondLastName, 'admin', @password, 0)";
                    MySqlCommand command = new MySqlCommand(sql, connection);

                    command.Parameters.AddWithValue("@CI", theUser.CI);
                    command.Parameters.AddWithValue("@firstName", theUser.FirstName);
                    command.Parameters.AddWithValue("@lastName", theUser.LastName);
                    command.Parameters.AddWithValue("@secondLastName", theUser.SecondLastName);
                    command.Parameters.AddWithValue("@password", CalculateSHA1(theUser.Password));
                    command.ExecuteNonQuery();
                    connection.Close();
                }

            }
            catch (Exception ex)
            {
                throw new DataAccessException(ex.Message);
            }
        }

        private string CalculateSHA1(object message)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] msg = Encoding.Default.GetBytes(message.ToString());

            return BitConverter.ToString(sha1.ComputeHash(msg)).ToString().Replace("-", "");
        }
    }
}
